//
//  ChooseIdCardTypeVC.swift
//  选择证件类型
//
//  Created by 千策万划-mini on 2025/5/2.
//

import Foundation

class ChooseIdCardTypeVC: BaseTableVC {

    var productCode: String = ""
    var modelOneItem: ModelUserIdentityInfoOneItem = .init()
    var modelList: [[ModelBtn]] = []
    var listSection: [Bool] = []
    private var startTime: String = ""
    
    // MARK: - lazy
    lazy var navView: BaseNavView = {
        let result = BaseNavView()
        result.resetNavBackTitle(title: "Card Type", rightView: nil)
        result.leftTop = XY(0, 0)
        result.blockBack = { [weak self] in
            guard let self = self else { return }
            self.viewDetainment.show()
        }
        return result
    }()
    lazy var btnConfirm: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(284), 58)
        result.setBackgroundImage(UIImage(named: "icon_bottom_btn_bg"), for: .normal)
        result.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-max(LEFT_MARGIN, getBottomSafeAreaHeight()))
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        
        let label = OutlineLabel()
        label.resetView(
            title: "Confirming",
            textColor: COLOR_WHITE(),
            font: UIFont.customExtraBoldFont(size: 20),
            shadowColor: UIColor(hex: "#004600"),
            outlineColor: UIColor(hex: "#1B4506")
        )
        label.centerXCenterY = XY(result.width/2, result.height/2)
        result.addSubview(label)
        return result
    }()

    // MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        startTime = GlobalMethod.getTimeStamp()
        configUI()
        requestList()
    }

    func configUI() {
        view.addSubview(navView)
        tableView.register(ChooseIdCardTypeCell.self, forCellReuseIdentifier: String(reflecting: ChooseIdCardTypeCell.self))
        tableView.height = SCREEN_HEIGHT - navView.bottom
        tableView.top = navView.bottom
        view.addSubview(btnConfirm)
        tableView.tableFooterView = { () -> UIView in
            let frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: max(LEFT_MARGIN, getBottomSafeAreaHeight())+62)
            let result = UIView(frame: frame)
            return result
        }()
    }

    // MARK: - tableView delegate
    func numberOfSections(in _: UITableView) -> Int {
        return modelList.count
    }

    override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
        let list = modelList[section]
        return listSection[section] == false ? 0 : list.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: String(reflecting: ChooseIdCardTypeCell.self), for: indexPath) as! ChooseIdCardTypeCell
        let list = modelList[indexPath.section]
        cell.resetCellWithModel(list[indexPath.row])
        cell.blockItemClick = { [weak self] cell in
            guard let self = self else { return }
            for section in 0 ..< self.modelList.count {
                for row in 0 ..< self.modelList[section].count {
                    self.modelList[section][row].isSelected = false
                }
            }
            if let indexPath = tableView.indexPath(for: cell) {
                self.modelList[indexPath.section][indexPath.row].isSelected = true
            }
            self.tableView.reloadData()
        }
        return cell
    }

    override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let list = modelList[indexPath.section]
        return ChooseIdCardTypeCell.fetchHeight(model: list[indexPath.row], className: nil, selectorName: "resetCellWithModel:")
    }

    override func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
        return W(61)
    }

    override func tableView(_: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = ChooseIdCardTypeSectionView()
        view.btnArrow.isSelected = listSection[section]
        view.resetTitle(title: section == 0 ? "Recommended ID Type" : "Other Options")
        view.blockSectionItemClick = { [weak self] in
            guard let self = self else { return }
            self.tableView.beginUpdates()
            self.listSection[section].toggle()
            let rowCount = self.modelList[section].count
            var indexPaths: [IndexPath] = []
            for row in 0 ..< rowCount {
                indexPaths.append(IndexPath(row: row, section: section))
            }
            if self.listSection[section] {
                self.tableView.insertRows(at: indexPaths, with: .fade)
            } else {
                self.tableView.deleteRows(at: indexPaths, with: .fade)
            }
            self.tableView.endUpdates()
        }
        return view
    }

    override func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat {
        return W(12)
    }
    
    
    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            // 获取所有被选中的 ModelBtn
            let selectedModels = modelList.flatMap { $0 }.filter { $0.isSelected ?? false }
            if !selectedModels.isEmpty {
                GlobalMethod.buryPoint(productCode: self.productCode, type: "2", startTime: self.startTime, endTime: GlobalMethod.getTimeStamp())
                let model = selectedModels.first
                let vc = IdCardUploadVC()
                vc.navTitle = model?.title ?? "";
                vc.productCode = self.productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            break
        default:
            break
        }
    }

    // MARK: - request
    override func requestList() {
        for group in modelOneItem.stayed {
            var btnGroup: [ModelBtn] = []
            for title in group {
                var btn = ModelBtn()
                btn.title = title
                btnGroup.append(btn)
            }
            modelList.append(btnGroup)
        }
        for _ in 0 ..< modelList.count {
            //listSection.append(i == 0)
            listSection.append(true)
        }
        tableView.reloadData()
    }

    // MARK: - 示例方法：设置图片显示
    func setupImageView(imageView: UIImageView) {
        imageView.contentMode = .scaleAspectFit  // 或者使用 .scaleAspectFill，取决于您的具体需求
        imageView.clipsToBounds = true
    }

}

// MARK: - 分组头
class ChooseIdCardTypeSectionView: UIView {

    var blockSectionItemClick: (() -> Void)?

    // MARK: - lazy
    lazy var viewBack: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(SCREEN_WIDTH, W(61))
        result.setBackgroundImage(UIImage(named: "icon_KYC_section_bg"), for: .normal)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()

    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var btnArrow: UIButton = {
        let result = UIButton()
        result.isUserInteractionEnabled = false
        result.widthHeight = XY(28, 28)
        result.setImage(UIImage(named: "icon_arrow_down"), for: .normal)
        result.setImage(UIImage(named: "icon_arrow_up"), for: .selected)
        return result
    }()

    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        widthHeight = XY(SCREEN_WIDTH, 0)
        backgroundColor = .clear
        addSubView()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 添加
    func addSubView() {
        addSubview(viewBack)
        viewBack.addSubview(labelTitle)
        viewBack.addSubview(btnArrow)
        resetView()
    }

    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        switch sender.tag {
        case 1:
            btnArrow.isSelected = !btnArrow.isSelected
            if let block = blockSectionItemClick {
                block()
            }
        default:
            break
        }
    }

    // MARK: - 重置界面
    func resetView() {
        viewBack.leftTop = XY(0, 0)
        btnArrow.rightCenterY = XY(SCREEN_WIDTH - 13, viewBack.height / 2)
        height = viewBack.bottom
    }

    func resetTitle(title: String = "") {
        labelTitle.resetView(
            title: UnPackStr(title),
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 18),
            shadowColor: UIColor(hex: "#4105A0"),
            outlineColor: UIColor(hex: "#3B0B9A")
        )
        labelTitle.leftCenterY = XY(13, viewBack.height / 2)
    }
}
